#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SIZE 4096


const char *Pathname = "/home/user_01/test/test_24_5_19/shm";
int proj_id = 0x11223344;

key_t GetKey()
{
    key_t key = ftok(Pathname, proj_id);
    if (key == -1)
    {
        std::cerr << "errno:" << errno << "errstring:" << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

std::string ToHex(key_t key)
{
    char buffer[1024];
    snprintf(buffer,sizeof(buffer),"0x%x",key);
    return buffer;
}

 int CreateShmHelper(key_t key, int flag)
 {
    int shmid = shmget(key, SIZE, flag);
    if( shmid < 0)
    {
        std::cerr << "errno:" << errno << "errstring:" << strerror(errno) << std::endl;
    }
    return shmid;
 }

int CreateShm(key_t key)
{
    //IPC_CREAT|IPC_EXCL:不存在就创建，存在就返回错误---->确保每一次生成一个全新的共享内存
    return CreateShmHelper(key, IPC_CREAT|IPC_EXCL|0644);
}

int GetShm(key_t key)
{
    return CreateShmHelper(key, IPC_CREAT/*0也可以*/);
}
